﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace DepartmentSystem
{
    public class SQLHelper
    {
        private static string connstr = "Data Source=LAPTOP-I9NLFD33\\MSSQLSERVER01;Initial Catalog=DepartmentSystem;Integrated Security=True";

        public static int executeNoQuery(string sql)
        {
            using (SqlConnection con = new SqlConnection(connstr))
            {
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    con.Open();
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        public static SqlDataReader executeReader(string sql)
        {
            SqlConnection con = new SqlConnection(connstr);

            using (SqlCommand cmd = new SqlCommand(sql, con))
            {
                try
                {
                    con.Open();
                    return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
                }
                catch (Exception)
                {
                    con.Close();
                    con.Dispose();
                    throw;
                }
            }
        }

        public static DataTable GetTable(string sql)
        {
            //实例化连接对象，并指定连接字符串，自动释放资源，不用关闭
            using (SqlConnection conn = new SqlConnection(connstr))
            {
                //数据适配器
                SqlDataAdapter adp = new SqlDataAdapter(sql, conn);

                //填充并返回数据表
                DataTable dt = new DataTable();
                adp.Fill(dt);
                return dt;
            }
        }

        public static DataTable GetTable(string sql, params SqlParameter[] param)
        {
            //实例化连接对象，并指定连接字符串，自动释放资源，不用关闭
            using (SqlConnection conn = new SqlConnection(connstr))
            {
                //数据适配器
                SqlDataAdapter adp = new SqlDataAdapter(sql, conn);
                if (param != null)
                {
                    //批量添加参数
                    adp.SelectCommand.Parameters.AddRange(param);
                }
                //填充并返回数据表
                DataTable dt = new DataTable();
                adp.Fill(dt);
                return dt;
            }
        }

        public static object QueryScalar(string sql)
        {
            SqlConnection con = new SqlConnection(connstr);

            using (SqlCommand cmd = new SqlCommand(sql, con))
            {
                try
                {
                    con.Open();
                    return cmd.ExecuteScalar();
                }
                catch (Exception)
                {
                    con.Close();
                    con.Dispose();
                    throw;
                }
            }
        }
    }
}